using System;
using EstimateTracker.DataAccess.Repositories;
using EstimateTracker.Domain.Entities;
using JetBrains.Annotations;

namespace EstimateTracker.Services
{
    public class TimerService : ITimerService
    {
        private readonly IHoursWorkedRepository _hoursWorkedRepository;
        private bool _previousTime = false;

        public TimerService([NotNull] IHoursWorkedRepository hoursWorkedRepository)
        {
            if (hoursWorkedRepository == null) throw new ArgumentNullException("hoursWorkedRepository");
            _hoursWorkedRepository = hoursWorkedRepository;
        }

        private double ConvertMinuteToDecimal(TimeSpan time)
        {
            int hours = time.Hours;
            double result = hours + time.Minutes/60.0;
            return Math.Round(result, 1);
        }

        public double UpdateTime(double hours, TimeSpan time)
        {
            return hours + ConvertMinuteToDecimal(time);
        }

        public double SaveHours(Task selectedTask, double time)
        {
            // TODO: Encapsulate the timespan object or use a service to create it instead?
            time = ConvertMinuteToDecimal(new TimeSpan(0, (int) time, 0));
            HoursWorked hoursWorked = new HoursWorked{DateAndTimeFinished = DateTime.Now,Hours = time,Task = selectedTask};
            _hoursWorkedRepository.Save(hoursWorked);
            return time;
        }
    }
}